package com.caochenlei.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caochenlei.domain.Result;
import com.caochenlei.domain.Tag;
import com.caochenlei.service.TagService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@Api(tags = "文章标签接口")
public class TagController {
    @Autowired
    private TagService tagService;

    //插入一条记录
    @PostMapping("/tags")
    @ApiOperation(value = "插入一条记录")
    @Secured({"ROLE_ADMIN"})
    public Result insert(@RequestBody Tag tag) {
        tag = tagService.insert(tag);
        if (tag.getId() != null) {
            return new Result(true, tag, "操作成功");
        } else {
            return new Result(false, null, "操作失败");
        }
    }

    //根据主键删除
    @DeleteMapping("/tags/{id}")
    @ApiOperation(value = "根据主键删除")
    @Secured({"ROLE_ADMIN"})
    public Result deleteById(@PathVariable("id") Integer id) {
        Integer rows = tagService.deleteById(id);
        if (rows > 0) {
            return new Result(true, rows, "操作成功");
        } else {
            return new Result(false, rows, "操作失败");
        }
    }

    //根据主键修改
    @PutMapping("/tags")
    @ApiOperation(value = "根据主键修改")
    @Secured({"ROLE_ADMIN"})
    public Result updateById(@RequestBody Tag tag) {
        Integer rows = tagService.updateById(tag);
        if (rows > 0) {
            return new Result(true, rows, "操作成功");
        } else {
            return new Result(false, rows, "操作失败");
        }
    }

    //根据主键查找
    @GetMapping("/common/tags/{id}")
    @ApiOperation(value = "根据主键查找")
    public Result selectById(@PathVariable("id") Integer id) {
        Tag tag = tagService.selectById(id);
        if (tag != null) {
            return new Result(true, tag, "操作成功");
        } else {
            return new Result(false, null, "操作失败");
        }
    }

    //根据条件查找
    @PostMapping("/common/tags/page")
    @ApiOperation(value = "根据条件查找")
    public Result search(@RequestBody Map<String, Object> searchMap) {
        Page<Tag> tagPage = tagService.search(searchMap);
        if (tagPage != null) {
            return new Result(true, tagPage, "操作成功");
        } else {
            return new Result(false, null, "操作失败");
        }
    }

    //查看热门标签
    @GetMapping("/common/tags/group")
    @ApiOperation(value = "查看热门标签", notes = "对标签名称进行分组，如果发现出现次数大于10，就证明这个标签是一个热门标签")
    public Result group() {
        List<Tag> tags = tagService.group();
        if (tags != null) {
            return new Result(true, tags, "操作成功");
        } else {
            return new Result(false, null, "操作失败");
        }
    }
}
